import Taro from '@tarojs/taro';
import u from 'updeep'
import request from '../util/request'

const INITDATA = {
  tableAry: [{
    name: '产品名称',
    value: 'title'
  }, {
    name: '介绍',
    value: 'description'
  }, {
    name: '联系方式',
    value: 'cellphone'
  }, {
    name: '联系人',
    value: 'contact'
  }],
  listData: {},
  id: '',
  loadUrl: 'product',
}
export default {
  namespace: 'businessDetail',
  state: {...INITDATA},
  reducers: {
    updateState(state, {payload}) {
      return u({
        ...payload
      }, state)
    },
    initData(state, action) {
      return {
        ...state,
        ...action.payload,
        ...INITDATA
      }
    }
  },
  effects: {
    // 获取列表数据
    * loadData({payload = {}}, {select, put, call}) {
      const {id, loadUrl} = yield select(({businessDetail}) => businessDetail)
      const {data} = yield call(request, {
        url: SERVERURL + `/service/${loadUrl}/` + id,
        data: {},
        method: 'GET',
      })
      if (data && data.data) {
        const d = data.data || {};
        yield put({
          type: 'updateState',
          payload: {
            listData: d,
          }
        })
      } else {
        Taro.showToast({
          title: (data || {}).msg || '获取列表数据失败',
          icon: 'none'
        })
      }
    },
    // 分享
    * sharePage({payload = {}}, {select, put, call}) {
      const {id, loadUrl} = yield select(({businessDetail}) => businessDetail)
      const {data} = yield call(request, {
        url: SERVERURL + `/service/${loadUrl}/addView?goodId=` + id,
        method: 'POST',
      })

      if (data && data === "unauthc") {
        Taro.navigateTo({
          url: `/pages/login/index`
        })
      }

      if (data && data.data) {
        const d = data.data || {};
        if (d.showCellphone) {
          yield put({
            type: 'updateState',
            payload: {
              listData: {
                showCellphone: d.showCellphone,
                cellphone: d.cellphone
              },
            }
          })
        }
      } else {
        Taro.showToast({
          title: (data || {}).msg || '分享失败',
          icon: 'none'
        })
      }
    },
  }
};
